<template>
  <div class="drugCostAnalysis-container">
    <el-form class="search" ref="queryF" size="small" label-width="100px" :model="queryF.data" :rules="queryF.rules">
      <el-row type="flex">
        <el-col :span="8">
          <el-form-item label="时间" prop="setlym">
            <el-date-picker
              v-model="queryF.data.setlym"
              value-format="yyyy-MM"
              style="width:100%"
              type="month"
              :clearable="false"
              :picker-options="queryF.pickerOptions.setlym"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="险种" prop="insutype">
            <el-select v-model="queryF.data.insutype" placeholder clearable>
              <el-option v-for="(item, index) in queryF.options.insutype" :key="index" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="就诊类型" prop="mdtrtType">
            <el-select v-model="queryF.data.mdtrtType" placeholder clearable>
              <el-option v-for="(item, index) in queryF.options.mdtrtType" :key="index" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row type="flex">
        <el-col :span="8">
          <el-form-item label="药品类型" prop="drugType">
            <el-select v-model="queryF.data.drugType" placeholder clearable>
              <el-option v-for="(item, index) in queryF.options.drugType" :key="index" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="药品分类" prop="drugClassType">
            <el-select v-model="queryF.data.drugClassType" placeholder clearable>
              <el-option v-for="(item, index) in queryF.options.drugClassType" :key="index" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="药品名称" prop="drugName">
            <el-input v-model="queryF.data.drugName" placeholder="请输入" />
          </el-form-item>
        </el-col>
      </el-row>
      <div class="query-buttons">
        <el-button class="reset" style="width:66px;">收起<i class="el-icon-arrow-up"></i></el-button>
        <el-button class="reset" @click="resetBtnClick">重置</el-button>
        <el-button type="primary" @click="queryBtnClick">查询</el-button>
      </div>
    </el-form>
    <div class="result">
      <div class="pannel-header">
        <div class="title">药品结算费用分析</div>
        <el-button type="primary" @click="queryBtnClick">导出</el-button>
      </div>
      <div class="pannel-content">
        <el-table
          ref="drugT"
          size="medium"
          v-loading="drugT.loading"
          border
          highlight-current-row
          :data="drugT.data"
          width="100%"
          :height="drugT.tableHeight"
          @sort-change="drugT_sortChangeFunc"
        >
          <el-table-column prop="drugName" label="药品名称" width="100" header-align="left" />
          <el-table-column prop="dosform" label="剂型" width="66" header-align="left" />
          <el-table-column prop="spec" label="规格" width="66" header-align="left" />
          <el-table-column prop="psntime" label="结算人次(人次)" width="133" header-align="left" sortable="custom" />
          <el-table-column prop="psncnt" label="结算人数(人)" width="118" header-align="left" sortable="custom" />
          <el-table-column prop="sumfee" label="药品费用(万元)/同比" width="170" align="right" header-align="left" sortable="custom">
            <template v-slot="{ row }">
              <span>{{ deal10000(row.sumfee) }}</span>
              <span style="margin:0 4px;">/</span>
              <span v-if="row.sumfeesr > 0" style="color:#F56C6C">{{ deal100(row.sumfeesr, true) }}</span>
              <span v-else-if="row.sumfeesr < 0" style="color:#13CB33">{{ deal100(row.sumfeesr, true) }}</span>
              <span v-else style="color:#FF9500">-</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="avgfee"
            label="次均费用(元)"
            width="133"
            align="right"
            header-align="left"
            :formatter="(r, c, v) => dealMoney(v)"
            sortable="custom"
          />
          <el-table-column
            prop="perpsnfee"
            label="人均费用(元)"
            width="133"
            align="right"
            header-align="left"
            :formatter="(r, c, v) => dealMoney(v)"
            sortable="custom"
          />
          <el-table-column prop="fundexp" width="191" align="right" header-align="left" sortable="custom">
            <template slot="header">
              基金支出(万元)/同比
              <el-tooltip popper-class="table-header-tooltip" effect="light" placement="bottom">
                <div slot="content">
                  单个药品的基金支出是根据药品相关结<br />算数据的范围内报销比例，根据药品费<br />用乘以范围内报销比例进行计算，统计<br />结果会有偏差
                </div>
                <i class="el-icon-warning-outline" style="font-size: 12px;color: rgba(0,0,0,0.45);"></i>
              </el-tooltip>
            </template>
            <template v-slot="{ row }">
              <span>{{ deal10000(row.fundexp) }}</span>
              <span style="margin:0 4px;">/</span>
              <span v-if="row.fundexpsr > 0" style="color:#F56C6C">{{ deal100(row.fundexpsr, true) }}</span>
              <span v-else-if="row.fundexpsr < 0" style="color:#13CB33">{{ deal100(row.fundexpsr, true) }}</span>
              <span v-else style="color:#FF9500">-</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="avgfundexp"
            label="次均基金支出(元)"
            width="138"
            align="right"
            header-align="left"
            :formatter="(r, c, v) => dealMoney(v)"
            sortable="custom"
          />
          <el-table-column
            prop="perpsnfundexp"
            label="人均基金支出(元)"
            width="138"
            align="right"
            header-align="left"
            :formatter="(r, c, v) => dealMoney(v)"
            sortable="custom"
          />
          <el-table-column
            prop="reimprop"
            label="报销比例"
            width="89"
            align="right"
            header-align="left"
            :formatter="(r, c, v) => deal100(v)"
            sortable="custom"
          />
          <el-table-column
            prop="selfpay"
            label="个人自负(元)"
            width="110"
            align="right"
            header-align="left"
            :formatter="(r, c, v) => dealMoney(v)"
            sortable="custom"
          />
          <el-table-column prop="avgselfpay" label="次均个人负担(元)/同比" width="180" align="right" header-align="left" sortable="custom">
            <template v-slot="{ row }">
              <span>{{ dealMoney(row.avgselfpay) }}</span>
              <span style="margin:0 4px;">/</span>
              <span v-if="row.avgselfpaysr > 0" style="color:#F56C6C">{{ deal100(row.avgselfpaysr, true) }}</span>
              <span v-else-if="row.avgselfpaysr < 0" style="color:#13CB33">{{ deal100(row.avgselfpaysr, true) }}</span>
              <span v-else style="color:#FF9500">-</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="72" align="center" fixed="right">
            <template v-slot="{ row }">
              <el-link type="primary" :underline="false" @click="drugTRow_detialBtnEvent(row)">查看</el-link>
            </template>
          </el-table-column>
        </el-table>
        <Pagination
          :current-page="drugT.page._pageNo"
          :page-size="drugT.page._pageSize"
          :total="drugT.page.total"
          @size-change="drugTPage_sizeChangeEvent"
          @current-change="drugTPage_currentChangeEvent"
        ></Pagination>
      </div>
    </div>
  </div>
</template>

<script>
import { getMapping } from '@/dict'
import drugCostAnalysisApi from '@/api/drugCostAnalysisApi'
import Pagination from '@/components/Pagination'
import XEUtils from 'xe-utils'

const pageDefault = {
  _pageNo: 1,
  total: 0,
  _pageSize: 10
}
const queryFDataDefault = {
  setlym: XEUtils.toDateString(XEUtils.getWhatMonth(new Date(), -1), 'yyyy-MM'),
  insutype: '',
  mdtrtType: '',
  drugType: '',
  drugClassType: '',
  drugName: ''
}
// import { treatmentServList } from "@/api/index.js"
export default {
  name: 'DrugCostAnalysis',
  components: { Pagination },
  data() {
    return {
      loading: true, //页面全局loading
      queryF: {
        fold: false,
        pickerOptions: {
          setlym: {
            disabledDate(time) {
              //只可以选择三年以内的年月
              return time.getTime() < XEUtils.getWhatYear(new Date(), -3)
            }
          }
        },
        options: {
          insutype: [{ value: '', label: '全部' }, ...getMapping('INSUTYPE')],
          mdtrtType: [{ value: '', label: '全部' }, ...getMapping('MDTRT_TYPE')],
          drugType: [{ value: '', label: '全部' }, ...getMapping('DRUG_TYPE')],
          drugClassType: [{ value: '', label: '全部' }, ...getMapping('DRUGLIST_TYPE')]
        },
        disabled: {},
        data: { ...queryFDataDefault },
        rules: {}
      },
      drugT: {
        tableHeight: 0,
        order: '',
        loading: false,
        page: { ...pageDefault },
        data: [],
        exportLoading: false
      }
    }
  },
  filters: {},
  watch: {
    jumpPage: {
      handler(newPage) {
        const val = Number(newPage)
        if (val) {
          this.jumpPage = val
        } else {
          this.jumpPage = ''
        }
      }
    }
  },
  computed: {},
  methods: {
    getHeight() {
      let calHeight = window.innerHeight - 160 - 50 - 32 - 12 - 50 - 30 - 13 - 20
      this.drugT.tableHeight = calHeight > 200 ? calHeight : 200
    },
    dealMoney(money, fh) {
      let money_str = XEUtils.toValueString(money)
      if (!money_str) {
        return '-'
      }
      if (money_str.indexOf('.') >= 0) {
        money_str = XEUtils.toFixed(money_str, 2)
      }
      if (fh) {
        return money > 0 ? '+' + money_str : money_str
      } else {
        return money_str
      }
    },
    deal100(num, fh) {
      let num_100 = XEUtils.multiply(num, 100)
      if (num_100 && num_100 !== 0) {
        return this.dealMoney(num_100, fh) + '%'
      } else {
        return ''
      }
    },
    deal10000(num) {
      let num_10000 = XEUtils.divide(num, 10000)
      if (num_10000 && num_10000 !== 0) {
        return this.dealMoney(num_10000)
      } else {
        return ''
      }
    },
    resetBtnClick() {
      this.queryF.data = { ...queryFDataDefault }
    },
    queryBtnClick() {
      this.drugT.page._pageNo = 1
      return this.drugT_list()
    },
    drugT_sortChangeFunc({  prop, order }) {
      if (order) {
        this.drugT.order = prop + ' ' + (order == 'descending' ? 'desc' : 'asc')
      } else {
        this.drugT.order = ''
      }
      this.queryBtnClick()
    },
    drugT_list() {
      this.drugT.loading = true

      drugCostAnalysisApi
        .getKc24T(this.drugT.page, this.queryF.data, this.drugT.order)
        .then(res => {
          this.drugT.data = res.data.list
          this.drugT.page.total = res.data.total
        })
        .finally(() => {
          this.drugT.loading = false
        })
    },
    drugTPage_sizeChangeEvent(pageSize) {
      this.drugT.page._pageNo = 1
      this.drugT.page._pageSize = pageSize
      this.drugT_list()
    },
    drugTPage_currentChangeEvent(pageNum) {
      this.drugT.page._pageNo = pageNum
      this.drugT_list()
    },
    drugTRow_detialBtnEvent(row) {
      let params = { drugCode: row.drugCode, drugName: row.drugName, dosform: row.dosform, spec: row.spec }
      this.$router.push({ name: 'RegnHosplvDrugFeeAna', params: params })
    },
    drugT_selectionChangeEvent(selection) {
      console.log('selectionChange', selection)
      this.drugT.selectRecords = selection
    },
    drugT_exportCommand() {
      this.drugT.exportLoading = true
      // personPayInfoApi
      //   .export(command)
      //   .then(res => {
      //     debugger
      //     if (res.type === 'application/json') {
      //       let reader = new FileReader()
      //       reader.onload = e => {
      //         let r = JSON.parse(e.target.result)
      //         this.$message({
      //           message: r.statusText,
      //           type: 'error',
      //           duration: 5 * 1000
      //         })
      //       }
      //       reader.readAsText(res)
      //     } else {
      //       let url = window.URL.createObjectURL(res, {
      //         type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
      //       })
      //       let link = document.createElement('a')
      //       link.style.display = 'none'
      //       link.href = url
      //       // 下载后文件名
      //       link.setAttribute('download', `核赔导出${new Date().getTime()}.xlsx`)
      //       document.body.appendChild(link)
      //       //点击下载
      //       link.click()
      //       document.body.removeChild(link) //下载完成移除元素
      //       window.URL.revokeObjectURL(url) //释放掉blob对象
      //     }
      //   })
      //   .catch(err => {
      //     this.$message({
      //       message: err,
      //       type: 'error',
      //       duration: 5 * 1000
      //     })
      //   })
      //   .finally(() => {
      //     this.drugT.exportLoading = false
      //   })
    }
  },
  created() {
    this.getHeight()
    window.addEventListener('resize', this.getHeight)
  },
  destroyed() {
    window.removeEventListener('resize', this.getHeight)
  },
  beforeRouteEnter(to, from, next) {
    if (from.name == 'RegnHosplvDrugFeeAna') {
      to.meta.isBack = true
    }
    next()
  },
  activated() {
    if (!this.$route.meta.isBack) {
      // 如果isBack是false，表明需要获取新数据，否则就不再请求，直接使用缓存的数据
      //清空表单

      this.queryF.data = { ...queryFDataDefault }
      this.drugT.data = []
      this.drugT.page = { ...pageDefault }
    }
    // 恢复成默认的false，避免isBack一直是true，导致下次无法获取数据
    this.$route.meta.isBack = false
  }
}
</script>

<style lang="less">
//气泡样式
.el-tooltip__popper.is-light.table-header-tooltip {
  border: 0;
  box-shadow:1px 2px 5px 2px #f2f3f6;
  .popper__arrow{
    border:0;
  }
}
.drugCostAnalysis-container {
  width: 100%;
  padding: 16px;
  height: calc(100% - 50px);
  min-width: 600px;
  min-height: 500px;
  background: #f5f7fa;
  display: flex;
  flex-flow: column nowrap;

  //表单样式
  .el-form-item .el-form-item__label {
    color: #303133;
  }
  .el-form-item .el-input__inner {
    color: #303133;
  }

  //表格样式
  .el-table {
    border: 0;
  }
  .el-table--border::after,
  .el-table--group::after,
  .el-table::before {
    background-color: transparent;
  }
  .el-table {
    thead th.el-table__cell {
      background: #f0f2f5;
      color: #303133;
      font-weight: 700;
      height: 40px;
      line-height: 40px;
      font-size: 14px;
      box-sizing: border-box;
    }
    .el-table--border {
      border-color: red;
    }
    .el-icon-question {
      color: #1890ff;
      font-size: 16px;
    }
    .el-table__empty-block {
      justify-content: flex-start;
    }
  }
  .el-table td.el-table__cell,
  .el-table th.el-table__cell.is-leaf {
    border-color: #cecece;
    height: 36px;
    line-height: 36px;
    padding: 0;
    color: #303133;
    letter-spacing: 0;
    .el-link--inner {
      color: #0160c0;
    }
    .caret-wrapper {
      width: 6px;
    }
  }
  .el-table td.el-table__cell {
    border-left: 0;
    border-bottom-color: #eceff5;
    border-right-color: #cfcfcf;
  }

  //表格排序样式
  .el-table .ascending .sort-caret.ascending {
    border-bottom-color: #0160c0;
  }
  .el-table .descending .sort-caret.descending {
    border-top-color: #0160c0;
  }

  .el-table--border .el-table__cell,
  .el-table__body-wrapper .el-table--border.is-scrolling-left ~ .el-table__fixed {
    border-color: #cecece;
  }
  .el-form-item--mini.el-form-item,
  .el-form-item--small.el-form-item {
    margin-bottom: 16px;
  }

  //按钮同一样式
  .el-button {
    width: 58px;
    height: 32px;
    border-radius: 2px;
    font-size: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 10px 0 0;
    color: #303133;
    i {
      font-size: 8px;
      color: #606266;
      margin-left: 4px;
    }
  }
  .el-button--primary {
    background: #0160c0;
    border-color: #0160c0;
    color: #fff;
  }

  //-----------------------------------------------------------------------
  //查询条件部分
  .search {
    margin-bottom: 12px;
    border-radius: 4px;
    background: #fff;
    box-sizing: border-box;
    position: relative;
    padding-top: 16px;
    .el-form-item__content {
      padding-right: 50px;
    }
    .el-select {
      width: 100%;
    }
    .query-buttons {
      width: 100%;
      display: flex;
      flex-flow: row nowrap;
      justify-content: flex-end;
      padding-bottom: 16px;
      padding-right: 40px;
    }
  }

  //pannel 部分
  .result {
    flex: 1;
    background: #fff;
    display: flex;
    flex-flow: column nowrap;

    //panel 头部
    .pannel-header {
      box-sizing: border-box;
      height: 50px;
      line-height: 50px;
      display: flex;
      justify-content: flex-end;
      align-items: center;
      position: relative;
      padding-right: 40px;
      .title {
        position: absolute;
        left: 18px;
        height: 16px;
        line-height: 16px;
        font-size: 16px;
        color: #303133;
        font-weight: 600;
        &::before {
          content: '';
          width: 4px;
          height: 14px;
          background: #0160c0;
          position: absolute;
          left: -8px;
          top: 0;
          bottom: 0;
          margin: auto;
        }
      }
    }

    .pannel-content {
      position: relative;
      flex: 1;
      margin: 0 20px 13px 20px;
    }
  }
}
</style>
